<template>
  <!-- 组织管理 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :inline="true" :model="filterForm">
          <el-form-item label="组织名称:" prop="orgName">
            <el-input v-model.trim="filterForm.orgName" style="width: 200px;margin-right:10px" maxlength="30" class="filter-item limit" clearable placeholder="请输入内容" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item label="组织编码:" prop="orgCode">
            <el-input v-model.trim="filterForm.orgCode" style="width: 200px;margin-right:10px" maxlength="30" class="filter-item limit" clearable placeholder="请输入内容" @keyup.enter.native="handleFilter" />
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button v-permission="['ORG_ADD_BUTTON']" type="primary" icon="el-icon-plus" @click="onAdd">新增</el-button>
          <!-- <el-button v-permission="['ORG_OPENALL_BUTTON']" icon="el-icon-folder-opened" @click="onExpandAll">展开</el-button> -->
          <el-button v-permission="['ORG_CLOSEALL_BUTTON']" icon="el-icon-folder" @click="onFoldAll">折叠</el-button>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          border
          :data="tableData"
          style="width: 100%;margin-bottom: 10px;"
          row-key="orgId"
          lazy
          :load="load"
          :default-expand-all="false"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :header-cell-style="headerCellStyle"
          :expand-row-keys="expandRowKeys"
        >
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column
            fixed="left"
            label="序号"
            type="index"
            width="70"
            :index="indexMethod"
          />
          <el-table-column
            v-if="columns[0].show"
            key="orgName"
            prop="orgName"
            label="组织名称"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[1].show"
            key="orgCode"
            prop="orgCode"
            label="组织编码"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[2].show"
            key="orgSort"
            prop="orgSort"
            label="排序"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[3].show"
            key="createTime"
            prop="createTime"
            label="创建时间"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :key="Math.random()"
            :fixed="$store.getters.device == 'mobile'? null :'right' "
            prop="action"
            label="操作"
            width="288"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-permission="['ORG_UPDATE_BUTTON']"
                size="mini"
                @click="onDetail(scope.row)"
              >查看
              </el-button>
              <el-button
                v-permission="['ORG_ADDCHILDREN_BUTTON']"
                size="mini"
                @click="onAddChildren(scope.row)"
              >新增下级
              </el-button>
              <el-button
                v-if="scope.row.orgCode != 'topOrg'"
                v-permission="['ORG_UPDATE_BUTTON']"
                size="mini"
                @click="onEdit(scope.row)"
              >修改
              </el-button>
              <!-- <el-popconfirm
                title="确定要删除这个机构吗？"
                style="padding: 7px"
                @confirm="onDelete(scope.row)"
              > -->
              <el-button
                slot="reference"
                v-permission="['ORG_DEL_BUTTON']"
                :disabled="scope.row.children && scope.row.children.length > 0 "
                size="mini"
                type="danger"
                @click="onDelete(scope.row)"
              >删除
              </el-button>
              <!-- </el-popconfirm> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="filterForm.pageNo"
          :limit.sync="filterForm.pageSize"
          @pagination="getList()"
        />
      </div>
      <OrgEdit ref="orgForm" />
    </div>
  </div>
</template>
<script>
import hrOrganizationApi from '@/framework/api/hrOrganization'
import { mapGetters } from 'vuex'
import Item from '@/framework/layout/components/Sidebar/Item'
import OrgEdit from './components/orgEdit.vue'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'
export default {
  name: 'OrganizationManageLazy',
  components: {
    Item,
    OrgEdit
  },
  mixins: [dialogColumn],
  data() {
    return {
      loading: false,
      filterForm: {
        orgName: '',
        orgCode: ''
      },
      // 列信息
      columns: [
        { prop: 'orgName', label: `组织名称`, show: true },
        { prop: 'orgCode', label: `组织编码`, show: true },
        { prop: 'orgSort', label: `顺序`, show: true },
        { prop: 'createTime', label: `创建时间`, show: true }
      ],
      tableData: [],
      total: 0,
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      expandRowKeys: [],
      insideDialogVisiable: false
    }
  },

  computed: {
    ...mapGetters(['roles', 'permission_routes'])
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.getList()
    },
    indexMethod(index) {
      return index + 1
    },
    // 获取页面列表
    getList(orgId) {
      this.loading = true

      if (this.filterForm.orgName != '' || this.filterForm.orgCode != '') { // 带参数分页
        hrOrganizationApi.pageList(this.filterForm).then((res) => {
          this.loading = false
          this.tableData = res.data.rows
          this.total = res.data.totalRows
          this.datasourceListLength = res.data.rows.length
        })
      } else { // 不带参数tree
        this.total = 0
        if (orgId) {
          hrOrganizationApi.listByDataScope({ orgId: orgId }).then(res => {
            let currentArea = []
            currentArea = res.data.map((item, index) => {
              item.hasChildren = true
              return item
            })
            const store = this.$refs.table.store
            // 顶部不能选根节点  不需要判断parentId是否为0
            const parent = store.states.lazyTreeNodeMap[orgId]
            // 判断是否展开子节点  若未展开parent为空
            if (parent) {
            // 改变原数组处理parent 待优化
              parent.splice(0, parent.length, ...currentArea)
            } else {
              // 如果父节点无法在lazyTreeNodeMap中查到  即parent为空 则刷新当前父节点  并且展开子节点
              this.$set(store.states.lazyTreeNodeMap, orgId, res.data)
              store.states.treeData[orgId] ? store.states.treeData[orgId].expanded = true : ''
            }
            this.loading = false
          })
        } else {
          hrOrganizationApi.listByDataScope({ orgId: 0 }).then(res => {
            if (res.success) {
              this.tableData = res.data.map((item, index) => {
                item.hasChildren = true
                item.children = []
                return item
              })
            }
            this.loading = false
          })
        }
      }
    },
    // 懒加载
    load(tree, treeNode, resolve) {
      hrOrganizationApi.listByDataScope({ orgId: tree.orgId }).then((res) => {
        if (res.data.length && res.data.length > 0) {
          const data = res.data.map((item, index) => {
            item.hasChildren = true
            item.children = []
            return item
          })
          resolve(data)
        } else {
          tree.hasChildren = false
        }
      })
    },
    /** 展开详情 */
    openDetail(row) {
      this.$nextTick(() => {
        this.$refs.table.toggleRowExpansion(row, true)
      })
    },
    // 搜索
    handleFilter() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      this.handleFilter()
    },
    // 点击新增组织按钮
    onAdd() {
      this.$refs.orgForm.openOrg('', 'add')
    },
    // 点击新增下级组织按钮
    onAddChildren(row) {
      this.$refs.orgForm.openOrg(row, 'addChildren')
      this.$set(row, 'hasChildren', true)
    },
    // 查看
    onDetail(row) {
      this.$refs.orgForm.openOrg(row, 'detail')
    },
    // 点击修改按钮
    onEdit(row) {
      this.$refs.orgForm.openOrg(row, 'update')
    },
    // 删除请求
    deleteOrg(row) {
      this.$dtMessageBox({ title: '提示', message: '确定要删除“' + row.orgName + '”吗?', type: 'warning' }).then(() => {
        hrOrganizationApi.delete({ orgId: row.orgId }).then(res => {
          this.$refs.orgForm.initTree()
          this.getList(row.orgParentId)
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
        }).catch(() => {
        // 取消不做操作
        })
      })
    },
    onExpandAll() {
      this.tableData.forEach(value => {
        this.$refs.table.toggleRowExpansion(value, true)
      })
    },
    // 折叠所有并初始化列表
    onFoldAll() {
      const treeData = this.$refs.table['store'].states.treeData
      for (const i in treeData) {
        treeData[i].loaded = false
        treeData[i].expanded = false
      }
    },
    // 删除
    onDelete(row) {
      this.deleteOrg(row)
    }
  }
}
</script>

<style lang="scss">
 .el-table__fixed-right {
height: 100%;
}
  .menu{
    margin: 20px;
  }
  .tableScopeSwitch .el-switch__label {
    position: absolute;
    display: none;
    padding-left: 4px;
    color: #fff;
  }
  /*打开时文字位置设置*/
  .tableScopeSwitch .el-switch__label--right {
    z-index: 1;
    right: 20px;
  }
  /*关闭时文字位置设置*/
  .tableScopeSwitch .el-switch__label--left {
    z-index: 1;
    left: 18px;
  }
  /*显示文字*/
  .tableScopeSwitch .el-switch__label.is-active {
    display: block;
  }
</style>

<style lang="scss" scoped>
  @import '@/framework/styles/variables';
  .el-dropdown-link {
    cursor: pointer;
    color: #F54A43;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
